﻿
//是否使用brdf 贴图
//#define _MODEL_BRDF_QUALITY_HIGH_

//#define _RES_WIN32_
#define _RES_ANDROID_
//#define _RES_IOS_

using UnityEngine;
using System.IO;
using UnityEditor;
using System.Collections.Generic;
using Object = UnityEngine.Object;
//using Dictionary = System.Collections.Generic.Dictionary<string,string>;


public class CommonUGUIABConfig
{
    public static string WindowsBuildPath = "builds";
    public static string AndroidBuildPath = "builds_android";
    public static string IOSBuildPath = "builds_ios";
    
    //资源地址
    public static string APPLICATION_PATH = Application.dataPath + "/";

    //工程地址
    public static string PROJECT_PATH = APPLICATION_PATH.Substring(0, APPLICATION_PATH.Length - 7);
    
    //AssetBundle打包的后缀名
    public static string SUFFIX = ".unity3d";
    
}

public class UGUIABConfig
{
    public static string TargetPath = "{0}/../../GameClient_GamePlay/{1}/AssetBundles/ui/slg_ugui";

    //此处添加需要命名assetBundleName的资源后缀名,注意大小写。
    public static Dictionary<string, string> suffixDirMap = new Dictionary<string, string>() {
        { ".prefab","prefab"},
        {  ".png","texpng"},
        { ".anim","anim"},
        { ".controller","controller"},
    };
}

public class NGUIABConfig
{
    public static string TargetPath = "{0}/../../GameClient_GamePlay/{1}/AssetBundles/ui/slg_ngui";

    //此处添加需要命名assetBundleName的资源后缀名,注意大小写。
    public static Dictionary<string, string> suffixDirMap = new Dictionary<string, string>() {
        { ".prefab","prefab"},
        {  ".mat","material"},
    };
}

public static class HUBuildUGUIBundle
{
    static private string m_ExportPath = string.Empty;

    static private string[] fullPaths = new string[0];

    static Dictionary<string, string> SuffixDirPathMap = new Dictionary<string, string>();

    //#if _MODEL_BRDF_QUALITY_HIGH_
    //	static string model_res_path = "model_res_high_quality";
    //    public static bool is_use_brdf_quality = true;
    //	public static string use_brdf_quality = "use BRDF HIGH Quality";
    //	static string quelity_end = "_high_quality";
    //#else
    //    static string model_res_path = "model_res";
    //    public static bool is_use_brdf_quality = false;
    //    public static string use_brdf_quality = "use SOSO Quality";
    //    static string quelity_end = "";
    //#endif

    //#if _RES_WIN32_
    //    public static string BuildsPath = "builds";
    //    public static string TargetType = "win32";
    //    public static BuildTarget BuildTargetOpt = BuildTarget.StandaloneWindows64;
    //#elif _RES_ANDROID_
    //	public static string BuildsPath = "builds_android";
    //	public static string TargetType = "android";
    //    public static BuildTarget BuildTargetOpt = BuildTarget.Android;
    //#elif _RES_IOS_
    //    public static string BuildsPath = "builds_ios";
    //    public static string TargetType = "ios";
    //    public static BuildTarget BuildTargetOpt = BuildTarget.iOS;
    //#endif

    #region UGUI 资源

    [MenuItem("New AB Editor/Build UGUI/Build For Windows")]
    public static void BuildUGUIForWindows()
    {
        MakeUguiResouceAb("builds");
        //string targetPath = string.Format(UGUIABConfig.TargetPath, Application.dataPath, CommonUGUIABConfig.WindowsBuildPath);

        //OneKeyToMakeUIBundleImpl(targetPath, BuildTarget.StandaloneWindows64, UGUIABConfig.suffixDirMap);
    }

    [MenuItem("New AB Editor/Build UGUI/Build For Android")]
    public static void BuildUGUIForAndroid()
    {
        MakeUguiResouceAb("builds_android");

        //string targetPath = string.Format(UGUIABConfig.TargetPath, Application.dataPath, CommonUGUIABConfig.AndroidBuildPath);

        //OneKeyToMakeUIBundleImpl(targetPath, BuildTarget.Android, UGUIABConfig.suffixDirMap);
    }

    [MenuItem("New AB Editor/Build UGUI/Build For IOS")]
    public static void BuildUGUIForIOS()
    {
        MakeUguiResouceAb("builds_ios");

        //string targetPath = string.Format(UGUIABConfig.TargetPath, Application.dataPath, CommonUGUIABConfig.IOSBuildPath);

        //OneKeyToMakeUIBundleImpl(targetPath, BuildTarget.iOS, UGUIABConfig.suffixDirMap);
    }
    #endregion

    #region NGUI 资源
    //[MenuItem("New AB Editor/Build NGUI/Build For Windows")]
    public static void BuildNGUIForWindows()
    {
        string targetPath = string.Format(NGUIABConfig.TargetPath, Application.dataPath, CommonUGUIABConfig.WindowsBuildPath);

        OneKeyToMakeUIBundleImpl(targetPath, BuildTarget.StandaloneWindows64, NGUIABConfig.suffixDirMap);
    }
    //[MenuItem("New AB Editor/Build NGUI/Build For Android")]
    public static void BuildNGUIForAndroid()
    {
        string targetPath = string.Format(NGUIABConfig.TargetPath, Application.dataPath, CommonUGUIABConfig.AndroidBuildPath);

        OneKeyToMakeUIBundleImpl(targetPath, BuildTarget.Android, NGUIABConfig.suffixDirMap);
    }
    //[MenuItem("New AB Editor/Build NGUI/Build For IOS")]
    public static void BuildNGUIForIOS()
    {
        string targetPath = string.Format(NGUIABConfig.TargetPath, Application.dataPath, CommonUGUIABConfig.IOSBuildPath);

        OneKeyToMakeUIBundleImpl(targetPath, BuildTarget.iOS, NGUIABConfig.suffixDirMap);
    }
    #endregion



    private static void OneKeyToMakeUIBundleImpl(string path,BuildTarget buildTarget,Dictionary<string,string> suffixDirMap)
    {
        SetExportPath(path);
        SetFilterInfo(suffixDirMap);
        
        if(fullPaths.Length == 0)
        {
            if (CheckSelectValid(ref fullPaths) == false)
            {
                return;
            }
        }        

        string messageStr = GetMessageStr(fullPaths);

        if (EditorUtility.DisplayDialog("制作AssetBundle确认", string.Format("你要制作AB包的来源为{0},输出目录为{1}", messageStr, m_ExportPath), "confirm", "cancel"))
        {
            string[] names = AssetDatabase.GetAllAssetBundleNames();
            if (names.Length != 0)
            {
                SetOrClearResourcesABName(CommonUGUIABConfig.APPLICATION_PATH, true);//有名字没清空，先把所有文件的AssetbundleName清空
            }

            for (int i = 0; i < fullPaths.Length; i++)
            {
                SetOrClearResourcesABName(fullPaths[i], false);//设置指定路径的文件或目录的ABname
            }

            AssetBundleManifest abm = BuildPipeline.BuildAssetBundles(
             m_ExportPath,
             BuildAssetBundleOptions.ChunkBasedCompression |
             BuildAssetBundleOptions.DeterministicAssetBundle,
             buildTarget);
            for (int i = 0; i < fullPaths.Length; i++)
            {
                SetOrClearResourcesABName(fullPaths[i], true);//打完ab包，清除指定路径的文件或目录的ABname
            }
        }
    }

    public static void MakeUguiResouceAb(string buildsPath)
    {
        string targetPath;
        BuildTarget targetBuild;
        if (buildsPath == "builds")
        {
            targetPath = string.Format(UGUIABConfig.TargetPath, Application.dataPath, CommonUGUIABConfig.WindowsBuildPath);
            targetBuild = BuildTarget.StandaloneWindows64;
        }
        else if(buildsPath == "builds_android")
        {
            targetPath = string.Format(UGUIABConfig.TargetPath, Application.dataPath, CommonUGUIABConfig.AndroidBuildPath);
            targetBuild = BuildTarget.Android;

        }
        else if(buildsPath == "builds_ios")
        {
            targetPath = string.Format(UGUIABConfig.TargetPath, Application.dataPath, CommonUGUIABConfig.IOSBuildPath);
            targetBuild = BuildTarget.iOS;

        }
        else
        {
            Debug.LogErrorFormat("no this config in HuBuildNewBundle,please check it");
            return;
        }

        //此处扩展目录
        fullPaths = new string[]
        {
            Application.dataPath + "/Resources/ugui/",
            Application.dataPath + "/Texture"
        };

        OneKeyToMakeUIBundleImpl(targetPath, targetBuild, UGUIABConfig.suffixDirMap);

    }

    //[MenuItem("New AB Editor/GetAllAssetBundleName")]
    static void GetAllAssetBundleName()
    {

        string[] names = AssetDatabase.GetAllAssetBundleNames();

        foreach (var name in names)
        {
            Debug.Log(name);
        }

    }

    //[MenuItem("New AB Editor/ClearAssetBundleName")]
    static void ClearResourcesAssetBundleName()
    {
        string[] fullPaths = GetSelectPaths();

        if (fullPaths.Length == 0)
        {
            if (EditorUtility.DisplayDialog("提示", "请至少选择一个目录或者文件", "ok"))
            {
                return;
            }
            return;
        }

        string messageStr = string.Empty;
        for (int i = 0; i < fullPaths.Length; i++)
        {
            messageStr += fullPaths[i] + "\r\n";
        }

        if (EditorUtility.DisplayDialog("清除AssetName名称确认", string.Format("你要清除AssetName的位置为{0}", messageStr), "confirm", "cancel"))
        {
            for (int i = 0; i < fullPaths.Length; i++)
            {
                SetOrClearResourcesABName(fullPaths[i], true);
            }
            EditorUtility.ClearProgressBar();
            AssetDatabase.RemoveUnusedAssetBundleNames();
        }

    }

    private static string GetMessageStr(string[] fullPaths)
    {
        string messageStr = "\r\n";
        for (int i = 0; i < fullPaths.Length; i++)
        {
            messageStr += fullPaths[i].Substring(Application.dataPath.Length) + "\r\n";
        }

        return messageStr;
    }

    private static bool CheckSelectValid(ref string[]  fullPath)
    {
         fullPath = GetSelectPaths();

        if (fullPath.Length == 0)
        {
            if (EditorUtility.DisplayDialog("提示", "请至少选择一个目录或者文件", "ok"))
            {
                return false;
            }
            return false;
        }
        else
        {
            return true;
        }

    }

    private static void SetFilterInfo(Dictionary<string,string> suffixDirMap)
    {
        SuffixDirPathMap = suffixDirMap;
    }

    private static void SetExportPath(string path)
    {
        m_ExportPath = path;

        if (Directory.Exists(m_ExportPath) == false)
        {
            Directory.CreateDirectory(m_ExportPath);
        }

    }

    private static void SetOrClearFileABName(FileInfo fileInfo, bool clear = false)
    {
        foreach (var item in SuffixDirPathMap)
        {
            string suffix = item.Key;
            string dirName = item.Value;

            if (fileInfo.Name.EndsWith(suffix, true, null))
            {
                string path = fileInfo.FullName.Replace('\\', '/').Substring(CommonUGUIABConfig.PROJECT_PATH.Length);
                var importer = AssetImporter.GetAtPath(path);
                if (importer)
                {
                    if (clear)
                    {
                        importer.assetBundleName = null;
                    }
                    else
                    {
                        string name = fileInfo.Name;
                        importer.assetBundleName = dirName + "/" + name.Substring(0, name.LastIndexOf('.')) + CommonUGUIABConfig.SUFFIX;
                    }
                }
            }
        }
    }


    static void SetOrClearResourcesABName(string fullPath, bool clear)
    {
        if (Directory.Exists(fullPath))
        {
            DirectoryInfo dir = new DirectoryInfo(fullPath);

            var files = dir.GetFiles("*", SearchOption.AllDirectories);
            ;
            for (var i = 0; i < files.Length; ++i)
            {
                var fileInfo = files[i];
                if (fileInfo.Name.EndsWith(".meta") && clear == false)//添加标记的时候meta过滤掉
                {
                    continue;
                }
                if (clear == false)
                {
                    EditorUtility.DisplayProgressBar("设置AssetName名称", "正在设置AssetName名称中...",
                    1f * i / files.Length);
                }
                else
                {
                    EditorUtility.DisplayProgressBar("清除AssetName名称", "正在清除AssetName名称中...",
                                        1f * i / files.Length);
                }

                SetOrClearFileABName(fileInfo, clear);
            }

        }
        else if (File.Exists(fullPath))
        {
            FileInfo fileInfo = new FileInfo(fullPath);

            SetOrClearFileABName(fileInfo, clear);
        }

        if (clear == true)
        {
            AssetDatabase.RemoveUnusedAssetBundleNames();
        }

        EditorUtility.ClearProgressBar();
    }

    static string[] GetSelectPaths()
    {
        UnityEngine.Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.Unfiltered);
        //此处添加需要命名的资源后缀名,注意大小写。
        string[] paths = new string[SelectedAsset.Length];

        for (int i = 0; i < paths.Length; i++)
        {
            paths[i] = CommonUGUIABConfig.PROJECT_PATH + AssetDatabase.GetAssetPath(SelectedAsset[i]);
        }

        return paths;
    }

    //static string GetSelectPath()
    //{
    //    UnityEngine.Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.Unfiltered);
    //    //此处添加需要命名的资源后缀名,注意大小写。
    //    if (!(SelectedAsset.Length == 1)) return string.Empty;

    //    string fullPath = SpineABConfig.PROJECT_PATH + AssetDatabase.GetAssetPath(SelectedAsset[0]);
    //    return fullPath;
    //}
}

